﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Data;
using System.Xml ;
using DevExpress.Utils.Menu;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Menu;
using System.Drawing;
using Fcdbas.WinUI.Forms;
using DevExpress.XtraSplashScreen;
using Fcdbas.WinUI.Controls;
using Fcdbas.Core;
using Fcdbas.Core.Reflection;
using Fcdbas.Platform.Properties;
using Fcdbas.Platform.Enums;
namespace Fcdbas.WinUI.Common
{
    public sealed class WinUtil
    {
        private Control frm;
        public static WinTranslate Translate = new WinTranslate("Fcdbas", "Fcdbas", "C", "");
        public WinUtil(Control frm)
        {
            this.frm = frm;
        }
        /// <summary>
        /// 加载网格的布局
        /// </summary>
        /// <param name="ctrl"></param>
        /// <param name="frm"></param>
        public void LoadGridLayouts(Control ctrl)
        {
            foreach (Control c in ctrl.Controls)
            {
                if (c is DevExpress.XtraGrid.GridControl)
                {
                    DevExpress.XtraGrid.GridControl gc = c as DevExpress.XtraGrid.GridControl;

                    GridView gridView = gc.MainView as GridView;
                    gridView.OptionsView.ShowGroupPanel = false;
                    gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                    gridView.OptionsSelection.MultiSelect = true;
                    //gridView.OptionsPrint.AutoWidth = false;
                    gridView.OptionsView.EnableAppearanceEvenRow = true;
                    gridView.OptionsView.EnableAppearanceOddRow = true;
                    if (gridView.OptionsView.ShowIndicator)
                        gridView.IndicatorWidth = 40;
                    LoadGridLayout(gc);
                    gridView.OptionsPrint.AutoWidth = false;
                    ((DevExpress.XtraGrid.Views.Grid.GridView)gc.MainView).CustomDrawRowIndicator += new RowIndicatorCustomDrawEventHandler(gridView_CustomDrawRowIndicator);
                    ((DevExpress.XtraGrid.Views.Grid.GridView)gc.MainView).OptionsView.ColumnAutoWidth = false;
                    ((DevExpress.XtraGrid.Views.Grid.GridView)gc.MainView).Appearance.Row.Font = new Font(AppEnvironment.AppOption.FontName, AppEnvironment.AppOption.FontSize);
                    ((DevExpress.XtraGrid.Views.Grid.GridView)gc.MainView).Appearance.EvenRow.BackColor = AppEnvironment.AppOption.EvenColor; //System.Drawing.Color.MistyRose;
                    ((DevExpress.XtraGrid.Views.Grid.GridView)gc.MainView).Appearance.OddRow.BackColor = AppEnvironment.AppOption.OddColor;
                }
                else
                    LoadGridLayouts(c);
            }
        }
        /// <summary>
        /// 加载网格的布局
        /// </summary>
        /// <param name="gc"></param>
        /// <param name="frm"></param>
        public void LoadGridLayout(DevExpress.XtraGrid.GridControl gc)
        {
            if (gc is cGridControl)
            {
                if (((cGridControl)gc).IsLoadLayout == true)
                    return;
            }
            string file = Application.StartupPath + "\\Layouts\\" + Process.GetCurrentProcess().ProcessName + "-" + frm.Name + "-" + gc.Name + ".xml";
            if (System.IO.File.Exists(file))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(file);
                bool load = true;
                XmlNode xn = doc.SelectSingleNode("XtraSerializer/property[@name='Columns']").SelectSingleNode("@value");
                GridView gv = gc.MainView as GridView;
                if (gv == null)
                    return;
                if (xn != null)
                {
                    if (xn.InnerText != null)
                    {
                        try
                        {
                            int cols = Convert.ToInt32(xn.InnerText);
                            
                            if (gv.Columns.Count != cols)
                                load = false;
                        }
                        catch (Exception ex)
                        {
                            Fcdbas.Core.Log.XTrace.WriteException(ex);
                        }
                    }
                }
                if (load)
                {
                    XmlNode colNode = doc.SelectSingleNode("XtraSerializer/property[@name='Columns']");
                    foreach (XmlNode node in colNode.ChildNodes)
                    {
                        XmlNode fieldNd = node.SelectSingleNode("property[@name='FieldName']");
                        XmlNode capNd = node.SelectSingleNode("property[@name='Caption']");
                        if (fieldNd != null && capNd != null)
                        {
                            GridColumn gc1 = gv.Columns.ColumnByFieldName(fieldNd.InnerText);
                            if (gc1 == null)
                            {
                                load = false;
                                break;
                            }
                            else
                            {
                                if (gc1.Caption != capNd.InnerText)
                                {
                                    load = false;
                                    break;
                                }
                            }
                        }
                    }
                }
                if(load)
                    gc.MainView.RestoreLayoutFromXml(file, DevExpress.Utils.OptionsLayoutBase.FullLayout);
            }
        }
        public void CreateGridPopupMenuToForm(Control ctrl)
        {
            foreach (Control c in ctrl.Controls)
            {
                if (c is WinUI.Controls.cGridControl)
                {
                    WinUI.Controls.cGridControl gc = c as WinUI.Controls.cGridControl;
                    CreateGridPopupMenu(gc);
                    
                }
                else
                    CreateGridPopupMenuToForm(c);
            }
        }
        private static void CreateGridPopupMenu(WinUI.Controls.cGridControl gc)
        {
            if (gc == null || gc.MainView == null)
                return;
            ((DevExpress.XtraGrid.Views.Grid.GridView)gc.MainView).PopupMenuShowing += new DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventHandler(WinUtil_PopupMenuShowing);
        }

        static void WinUtil_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            if (e.MenuType == DevExpress.XtraGrid.Views.Grid.GridMenuType.Column)
            {
                DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view == null)
                    return;
                WinUI.Controls.cGridControl gc = view.GridControl as WinUI.Controls.cGridControl;
                if(gc == null)
                    return;
              //  if (gc.IsInitPopupMenu)
             //       return;
                Control ctrl = gc.Parent;
                while(ctrl.Parent != null)
                {
                    ctrl = ctrl.Parent;
                }
                WinUI.Common.WinTranslate slate =null;
                if(ctrl is WinUI.Forms.BaseForm)
                {
                    slate = ((WinUI.Forms.BaseForm)ctrl).translate;
                }
                DevExpress.XtraGrid.Menu.GridViewColumnMenu menu = e.Menu as DevExpress.XtraGrid.Menu.GridViewColumnMenu;
                string caption = "查找替换";
                if (slate != null)
                    caption = slate.XlateWord("", caption);
                DXMenuItem findRep = new DXMenuItem(caption, new EventHandler(OnFindReplaceClick), Fcdbas.WinUI.Properties.Resources.FindDialogExcel);
                findRep.Tag = menu.Column;
                findRep.BeginGroup = true;
                e.Menu.Items.Add(findRep);


                caption = "显示统计";
                if (slate != null)
                    caption = slate.XlateWord("", caption);
                //DXMenuItem summary = new DXMenuItem(caption, new EventHandler(OnFindReplaceClick), Fcdbas.WinUI.Properties.Resources.AutoSum);
                DXMenuCheckItem summary = new DXMenuCheckItem(caption, false, Fcdbas.WinUI.Properties.Resources.AutoSum, new EventHandler(OnSummaryClick));
                summary.Tag = gc;
                summary.BeginGroup = true;
                e.Menu.Items.Add(summary);

                caption = "导出";
                if(slate != null)
                    caption = slate.XlateWord("",caption);
                DXSubMenuItem export = new DXSubMenuItem(caption);

                e.Menu.Items.Add(export);

                caption = "导出到Excel";
                if(slate != null)
                    caption = slate.XlateWord("",caption);
                DXMenuItem exportExcel = new DXMenuItem(caption, new EventHandler(OnExportExcelClick), Fcdbas.WinUI.Properties.Resources.ExportExcel);
                exportExcel.Tag = gc;
                exportExcel.BeginGroup = true;
                export.Items.Add(exportExcel);
                caption = "导出到Pdf";
                if (slate != null)
                    caption = slate.XlateWord("", caption);
                DXMenuItem exportPdf = new DXMenuItem(caption, new EventHandler(OnExportPdfClick), Fcdbas.WinUI.Properties.Resources.ExportParadox);
                exportPdf.Tag = gc;

                export.Items.Add(exportPdf);

                caption = "导出到Html";
                if (slate != null)
                    caption = slate.XlateWord("", caption);
                DXMenuItem exportHtml = new DXMenuItem(caption, new EventHandler(OnExportHtmlClick), Fcdbas.WinUI.Properties.Resources.ExportHtmlDocument);
                exportHtml.Tag = gc;

                export.Items.Add(exportHtml);

                caption = "导出到Doc";
                if (slate != null)
                    caption = slate.XlateWord("", caption);
                DXMenuItem exportDoc = new DXMenuItem(caption, new EventHandler(OnExportDocClick), Fcdbas.WinUI.Properties.Resources.ExportWord);
                exportDoc.Tag = gc;

                export.Items.Add(exportDoc);

                caption = "导出到Txt";
                if (slate != null)
                    caption = slate.XlateWord("", caption);
                DXMenuItem exportTxt = new DXMenuItem(caption, new EventHandler(OnExportTxtClick), Fcdbas.WinUI.Properties.Resources.ExportTextFile);
                exportPdf.Tag = gc;

                export.Items.Add(exportTxt);
                caption = "从Excel导入";
                if (slate != null)
                    caption = slate.XlateWord("", caption);
                DXMenuItem import = new DXMenuItem(caption, new EventHandler(OnImportClick), Fcdbas.WinUI.Properties.Resources.table_import);
                import.Tag = gc;
                import.BeginGroup = true;
                e.Menu.Items.Add(import);

                caption = "打印";
                if (slate != null)
                    caption = slate.XlateWord("", caption);
                DXMenuItem print = new DXMenuItem(caption, new EventHandler(OnPrintClick), Fcdbas.WinUI.Properties.Resources.PrintAreaSetPrintArea);
                print.Tag = gc;
                print.BeginGroup = true;
                e.Menu.Items.Add(print);

                caption = "合并单元格";
                if (slate != null)
                    caption = slate.XlateWord("", caption);
                DXMenuCheckItem merge = new DXMenuCheckItem(caption, false, Fcdbas.WinUI.Properties.Resources.MergeOrSplitCells, new EventHandler(OnCellMergeClick));
                merge.Tag = view;
                e.Menu.Items.Add(merge);

                //caption = "显示行号";
                //if (slate != null)
                //    caption = slate.XlateWord("", caption);
                //DXMenuCheckItem merge = new DXMenuCheckItem(caption, false, Fcdbas.WinUI.Properties.Resources.MergeOrSplitCells, new EventHandler(OnCellMergeClick));
                //merge.Tag = view;
                //e.Menu.Items.Add(merge);


                
                if (menu.Column != null)
                {
                    caption = "自定义显示";
                    if (slate != null)
                        caption = slate.XlateWord("", caption);
                    DXMenuItem style = new DXMenuItem(caption, new EventHandler(OnStyleConditionClick), Fcdbas.WinUI.Properties.Resources.StylesModifyStyle);
                    style.Tag = menu.Column;

                    e.Menu.Items.Add(style);
                }

                
                if (menu.Column != null)
                {
                    caption = "取消冻结";
                    if(slate != null)
                        caption = slate.XlateWord("",caption);

                    menu.Items.Add(CreateCheckItem(caption, menu.Column, FixedStyle.None, Fcdbas.WinUI.Properties.Resources.ObjectsAlignDistributeHorizontallyRemove));
                    caption = "冻结到左边";
                    if (slate != null)
                        caption = slate.XlateWord("", caption);
                    menu.Items.Add(CreateCheckItem(caption, menu.Column, FixedStyle.Left, Fcdbas.WinUI.Properties.Resources.ObjectsAlignLeft));
                    caption = "冻结到右边";
                    if (slate != null)
                        caption = slate.XlateWord("", caption);
                    menu.Items.Add(CreateCheckItem(caption, menu.Column, FixedStyle.Right, Fcdbas.WinUI.Properties.Resources.ObjectsAlignRightSmart));

                }

                //gc.IsInitPopupMenu = true;


            }
        }
        static void OnStyleConditionClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            GridColumn column = item.Tag as GridColumn;
            ConditionsEditor editor = new ConditionsEditor(column);
            
            editor.ShowDialog();
        }
        static void OnCellMergeClick(object sender, EventArgs e)
        {
            DXMenuCheckItem item = sender as DXMenuCheckItem;
            DevExpress.XtraGrid.Views.Grid.GridView view = item.Tag as DevExpress.XtraGrid.Views.Grid.GridView;
            view.OptionsView.AllowCellMerge = item.Checked;
        }
        static void OnFindReplaceClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            GridColumn column = item.Tag as GridColumn;
            dlgReplace dlg = new dlgReplace(column);
            dlg.ShowDialog();
        }
        static void OnSummaryClick(object sender, EventArgs e)
        {
            DXMenuCheckItem item = sender as DXMenuCheckItem;
            WinUI.Controls.cGridControl gc = item.Tag as WinUI.Controls.cGridControl;
            GridView view = gc.MainView as GridView;
            //if (item.Checked)
            //    item.Checked = false;
            //else
            //    item.Checked = true;
           // view.OptionsView.ShowFooter = item.Checked;
            if (item.Checked)
            {
                dlgGridSummarySet dlg = new dlgGridSummarySet(gc);
                dlg.ShowDialog();
                
                gc.RefreshDataSource();
                gc.Refresh();
            }
        }
        static void OnExportExcelClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            WinUI.Controls.cGridControl gc = item.Tag as WinUI.Controls.cGridControl;
            ExportGrid(gc, "xls", false);
        }
        static void OnExportPdfClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            WinUI.Controls.cGridControl gc = item.Tag as WinUI.Controls.cGridControl;
            ExportGrid(gc, "pdf", false);
        }
        static void OnExportDocClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            WinUI.Controls.cGridControl gc = item.Tag as WinUI.Controls.cGridControl;
            ExportGrid(gc, "doc", false);
        }
        static void OnExportHtmlClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            WinUI.Controls.cGridControl gc = item.Tag as WinUI.Controls.cGridControl;
            ExportGrid(gc, "html", false);
        }
        static void OnExportTxtClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            WinUI.Controls.cGridControl gc = item.Tag as WinUI.Controls.cGridControl;
            ExportGrid(gc, "txt", false);
        }

        static void OnPrintClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            WinUI.Controls.cGridControl gc = item.Tag as WinUI.Controls.cGridControl;
            gc.ShowRibbonPrintPreview();
        }
        static void OnImportClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            WinUI.Controls.cGridControl gc = item.Tag as WinUI.Controls.cGridControl;
            if (gc == null || gc.DataSource == null)
            {
                WinTranslate.GetTranslate().ShowMessage("网格没有绑定数据源，不能导入！", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            DataSourceBinding dsb = gc.DataSource as DataSourceBinding;
            if (dsb.Updates == UpdatesSql.ReadOnly )//|| !dsb.AllowNew)
            {
                WinTranslate.GetTranslate().ShowMessage("网格绑定的数据源是只读的，不能导入！", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.DefaultExt = "XLS";
            openDlg.Filter = "Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx";
            if (openDlg.ShowDialog() == DialogResult.OK)
            {
                List<string> list = Biz.FndDAL.GetExcelSheet(openDlg.FileName);
                if (list.Count == 0)
                {
                   // WinTranslate.GetTranslate().ShowMessage("文件读取错误或者文件没有包含Sheet!");
                    return;
                }
                dlgSelectSheet dlg = new dlgSelectSheet(list);
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    DataSet ds = Biz.FndDAL.ToDataTable(openDlg.FileName, dlg.Sheet);
                    if (ds == null || ds.Tables.Count == 0)
                    {
                      //  WinTranslate.GetTranslate().ShowMessage("文件读取错误,请详细检查！");
                        return;
                    }
                    BaseForm frm = gc.FindForm() as BaseForm;
                    SplashScreenManager.ShowForm(frm, typeof(SaveSplashScreen), true, true, false);
                    SplashScreenManager.Default.SendCommand(LoadStatus.ShowTitle, "正在导入数据，请稍候...");
                    SplashScreenManager.Default.SendCommand(LoadStatus.ShowProgress, "已经导入0条记录");
                    StringBuilder sb = new StringBuilder();
                    DataTable dt = ds.Tables[0];
                    GridView gv = gc.MainView as GridView;
                   
                    foreach (DataRow dr in dt.Rows)
                    {
                        string attr = "";
                        foreach (GridColumn gCol in gv.Columns)
                        {
                            if (dt.Columns.Contains(gCol.Caption) && dr[gCol.Caption] != null)
                            {
                                if (string.IsNullOrEmpty(dr[gCol.Caption].ToString()))
                                    continue;
                                ClientSys.AddToAttr(gCol.FieldName, dr[gCol.Caption].ToString(), ref attr);
                            }
                        }
                        if (string.IsNullOrEmpty(attr))
                            continue;
                        if (sb == null)
                            sb = new StringBuilder(attr);
                        else
                            ClientSys.AddAttrToGroup(sb, attr);
                        
                    }

                    if (frm != null)
                    {
                        frm.ImportToGrid(gc,sb.ToString(),dsb);
                        gc.RefreshDataSource();
                    }
                    SplashScreenManager.CloseForm(false);
                }
            }
           // gc.ShowRibbonPrintPreview();
        }
        static DXMenuCheckItem CreateCheckItem(string caption, GridColumn column, FixedStyle style, Image image)
        {
            DXMenuCheckItem item = new DXMenuCheckItem(caption, column.Fixed == style, image, new EventHandler(OnFixedClick));
            if (style == FixedStyle.None)
                item.BeginGroup = true;
            item.Tag = new MenuInfo(column, style);
            return item;
        }
        static void OnFixedClick(object sender, EventArgs e)
        {
            DXMenuItem item = sender as DXMenuItem;
            MenuInfo info = item.Tag as MenuInfo;
            if (info == null) return;
            info.Column.Fixed = info.Style;
        }
        class MenuInfo
        {
            public MenuInfo(GridColumn column, FixedStyle style)
            {
                this.Column = column;
                this.Style = style;
            }
            public FixedStyle Style;
            public GridColumn Column;
        }
        public void SaveGridLayout(cGridControl gc)
        {
            string file = Application.StartupPath + "\\Layouts\\";
            if (!System.IO.Directory.Exists(file))
                System.IO.Directory.CreateDirectory(file);
            file += System.Diagnostics.Process.GetCurrentProcess().ProcessName + "-" + frm.Name + "-" + gc.Name + ".xml";
            if (gc.IsClearLayout)
            {
                Fcdbas.Core.Util.FileHelper.DeleteFile(file, "");
            }
            else
                gc.MainView.SaveLayoutToXml(file,DevExpress.Utils.OptionsLayoutBase.FullLayout);
        }
        /// <summary>
        /// 导出网格的数据
        /// </summary>
        /// <param name="gc">要导出的网格</param>
        /// <param name="filetype">导出文件类型，pdf,xls,doc,html,txt</param>
        /// <param name="isOpen">是否自动打开</param>
        public static void ExportGrid(DevExpress.XtraGrid.GridControl gc,string filetype,bool isOpen)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            switch (filetype)
            {
                case "pdf":
                    sfd.DefaultExt = ".pdf";
                    sfd.Filter = "pdf Files(*.pdf)|*.pdf";
                    break;
                case "xls":
                    sfd.DefaultExt = ".xls";
                    sfd.Filter = "xls Files(*.xls)|*.xls";
                    sfd.FilterIndex = 1;
                    break;

                case "doc":
                    sfd.DefaultExt = ".doc";
                    sfd.Filter = "doc Files(*.doc)|*.doc";
                    sfd.FilterIndex = 1;
                    break;

                case "html":
                    sfd.DefaultExt = ".html";
                    sfd.Filter = "html Files(*.html)|*.html";
                    sfd.FilterIndex = 1;
                    break;

                case "txt":
                    sfd.DefaultExt = ".txt";
                    sfd.Filter = "txt Files(*.txt)|*.txt";
                    sfd.FilterIndex = 1;
                    break;
                default:
                    sfd.DefaultExt = ".xls";
                    sfd.Filter = "xls Files(*.xls)|*.xls";
                    sfd.FilterIndex = 1;
                    break;
            }
            sfd.RestoreDirectory = true;
            DialogResult dlgr = sfd.ShowDialog();
            if (dlgr != DialogResult.Cancel)
            {
                string file = sfd.FileName;
                //saveFileDialog1.FilterIndex = 2;


                switch (filetype)
                {
                    case "pdf":
                        gc.ExportToPdf(file);
                        break;
                    case "xls":
                       // DevExpress.XtraPrinting.XlsExportOptions option =new DevExpress.XtraPrinting.XlsExportOptions ();
                        //option.
                        gc.MainView.ExportToXls(file);//.ExportToXls(file);
                        break;

                    case "doc":
                        gc.ExportToRtf(file);
                        break;

                    case "html":

                        gc.ExportToHtml(file);
                        break;

                    case "txt":
                        gc.ExportToText(file);
                        break;
                    default:
                        gc.ExportToXls(file);
                        break;
                }
                //是否直接打開文件
                if (isOpen)
                {
                    ProcessStartInfo pInfo = new ProcessStartInfo();
                    pInfo.FileName = sfd.FileName;
                    Process p = Process.Start(pInfo);
                }
            }
        }
        public void SaveGridLayouts(Control ctrl)
        {
            foreach (Control c in ctrl.Controls)
            {
                if (c is DevExpress.XtraGrid.GridControl)
                {
                    cGridControl gc = c as cGridControl;
                    
                    SaveGridLayout(gc);
                }
                else
                    SaveGridLayouts(c);
            }
        }
        static void gridView_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            GridView view = sender as GridView;
            if (view == null)
                return;
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle >= 0)
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                switch (e.RowHandle.ToString().Length)
                {
                    case 1:
                    case 2:
                        if(view.IndicatorWidth <30)
                            view.IndicatorWidth = 30;
                        break;
                    case 3:
                        if(view.IndicatorWidth < 40)
                            view.IndicatorWidth = 40;
                        break;
                    case 4:
                        if(view.IndicatorWidth < 50)
                            view.IndicatorWidth = 50;
                        break;
                    case 5:
                        if(view.IndicatorWidth < 60)
                            view.IndicatorWidth = 60;
                        break;
                }

            }
           

            DataSourceBinding dsb = view.DataSource as DataSourceBinding;
            if(dsb == null)
                return;
            if (dsb.List != null && dsb.List.Count > e.RowHandle && e.RowHandle >= 0)
            {

                Fcdbas.Core.IEntity en = view.GetRow(e.RowHandle) as Fcdbas.Core.IEntity;
                if (en != null)
                {
                    if (en.Status == Core.RecordStatus.New)
                        e.Info.DisplayText = "N";
                    else if (en.Status == Core.RecordStatus.Delete)
                        e.Info.DisplayText = "D";
                    else if (en.Status == Core.RecordStatus.Edit)
                        e.Info.DisplayText = "E";
                }
            }
        }
        /// <summary>
        /// 取得控件最顶层的父窗口
        /// </summary>
        /// <param name="ctrl"></param>
        /// <returns></returns>
        public static Form GetParentForm(Control ctrl)
        {
            Control p = ctrl;
            while (p.Parent != null)
            {
                p = p.Parent;
                if (p is BaseForm)
                    break;
            }
            return p as Form;
        }
        public static string GetFormatMask(string format)
        {
            switch (format.ToUpper())
            {
                case "CURRENCY":
                    return "c";
                case "PERCENTAGE":
                    return "p";
                case "DECIMAL":
                    return "f";
                case "INTEGER":
                    return "d";
                case "UNFORMATTED":
                    return "";
                default:
                    return format;
            }
        }
        public static void Paste(IEntity en, string attr, DataSourceBinding dsb)
        {
            if (string.IsNullOrEmpty(attr))
                return;
            string[] fields = attr.Split(EntityBase.Record_Separator);
            foreach (string field in fields)
            {
                string[] vals = field.Split(EntityBase.Field_Separator);
                if (vals == null || vals.Length != 2)
                {
                    continue ;
                }
                DataItem di = dsb.Columns.Find(p => p.ColumnName.ToLower() == vals[0].ToLower());
                if (di == null || di.FieldType == FieldType.blob || di.FieldType == FieldType.Null)
                    continue;
                try
                {
                    if (di != null && di.Flags != DataItemFlags.ParentKey && (di.Insertable || di.UpdateOption == DataItemUpdate.Allow || (di.UpdateOption == DataItemUpdate.AllowedIfNull && en[vals[0].ToLower()] != null)))
                        en[vals[0].ToLower()] = vals[1];
                }
                catch
                {
                }
            }
        }
        /// <summary>
        /// 取得实体某个属性值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="en">要取得实体值</param>
        /// <param name="attribute">属性名称</param>
        /// <returns></returns>
        public static T GetEntityValue<T>(IEntity en, string attribute)
        {
            if (en == null)
                return default(T);
            
            object obj = en[attribute];
            if (obj == null)
                return default(T);
            if (obj is T) return (T)obj;
            return (T)Convert.ChangeType(obj, typeof(T));
        }
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
        private static extern IntPtr GetFocus();

        /// <summary>
        /// 当前拥有焦点的控件
        /// </summary>
        /// <param name="formControl"></param>
        /// <returns></returns>
        public static Control GetFocusedControl()
        {
            Control focusedControl = null;

            try
            {
                IntPtr focusedHandle = GetFocus();

                if (focusedHandle != IntPtr.Zero)
                {
                    focusedControl = Control.FromChildHandle(focusedHandle);
                }
            }
            catch { }

            return focusedControl;
        }
       
        /// <summary>
        ///  设置当前获得焦点的控件的下一控件（Tab顺序）为当前焦点控件
        /// </summary>
        public static void SetNextControlFocused(Control formControl)
        {
            Control ctlFocused = GetFocusedControl();
            if (ctlFocused != null)
            {
                Control ctl = formControl.FindForm().GetNextControl(ctlFocused, false);
                if (ctl == null)
                {
                    ctl = formControl.FindForm().GetNextControl(ctlFocused, true);
                }
                if (ctl != null)
                {
                    ctl.Focus();
                }
            }
        }
        //public void LoadBaseData(Control ctrl)
        //{
        //    foreach (Control c in ctrl.Controls)
        //    {
        //        if (c is WinUI.Controls.BaseInfoCtrl)
        //        {
        //            WinUI.Controls.BaseInfoCtrl gc = c as WinUI.Controls.BaseInfoCtrl;
        //            if (gc != null)
        //                gc.LoadData();
        //            //LoadBaseData(gc);
        //        }
        //        else
        //            LoadBaseData(c);
        //    }
        //}
    }
    public enum LoadStatus
    {
        ShowProgress,
        ShowCopyRight,
        ShowTitle
    }
}
